from fastapi import APIRouter, Depends, Query, HTTPException
from sqlalchemy.orm import Session
from typing import List, Dict, Any
from app.database.session import get_db
from app.schemas.chat import (
    ChatSession, ChatSessionCreate, ChatSessionUpdate,
    ChatMessage, ChatRequest
)
from app.schemas.user import User
from app.services.chat import ChatService
from app.api.dependencies import get_current_user  # 确保该依赖用于获取当前用户

router = APIRouter(
    prefix="/chats",
    tags=["聊天"]
)

# 会话管理接口
@router.post("/sessions", response_model=ChatSession, status_code=201)
def create_chat_session(
    session_in: ChatSessionCreate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """创建新的聊天会话"""
    return ChatService.create_chat_session(db, current_user.id, session_in)

@router.get("/sessions", response_model=List[ChatSession])
def get_chat_sessions(
    skip: int = Query(0, ge=0),
    limit: int = Query(100, ge=1, le=1000),
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取当前用户的所有会话"""
    return ChatService.get_chat_sessions(db, current_user.id, skip, limit)

@router.get("/sessions/{session_id}", response_model=ChatSession)
def get_chat_session(
    session_id: int,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取特定会话详情"""
    return ChatService.get_chat_session(db, current_user.id, session_id)

@router.put("/sessions/{session_id}", response_model=ChatSession)
def update_chat_session(
    session_id: int,
    session_update: ChatSessionUpdate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """更新会话信息"""
    return ChatService.update_chat_session(db, current_user.id, session_id, session_update)

@router.delete("/sessions/{session_id}", status_code=204)
def delete_chat_session(
    session_id: int,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """删除会话"""
    ChatService.delete_chat_session(db, current_user.id, session_id)
    return None

# 消息管理接口
@router.get("/sessions/{session_id}/messages", response_model=List[ChatMessage])
def get_session_messages(
    session_id: int,
    skip: int = Query(0, ge=0),
    limit: int = Query(100, ge=1, le=1000),
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取会话的历史消息"""
    return ChatService.get_session_messages(db, current_user.id, session_id, skip, limit)

# 核心聊天接口
@router.post("/message", response_model=Dict[str, Any])
def chat(
    chat_request: ChatRequest,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """与豆包AI大模型对话"""
    try:
        session, user_message, ai_message = ChatService.chat_with_ai(
            db, current_user.id, chat_request
        )
        return {
            "session": session,
            "user_message": user_message,
            "ai_message": ai_message
        }
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"聊天失败: {str(e)}"
        )